/**
 * Description: 使用poll实现IO多路复用客户端
 * File: server.c |Time: 2021-04-16 17:00
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>

#define ERR(msg) do {   \
    perror(msg);        \
    fprintf(stderr, "[err at]%s:%s:%d\n", __FILE__, __func__, __LINE__); \
    exit(EXIT_FAILURE); \
} while (0)

#define BUF_SIZE 128

typedef struct sockaddr * saddr;


int main(int argc, char *argv[])
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd) {
        ERR("socket");
    }

    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (-1 == connect(sockfd, (saddr)&serveraddr, sizeof(serveraddr))) {
        ERR("connect");
    }

    char buf[BUF_SIZE];
    int rw_bytes;
    while (1) {
        bzero(buf, BUF_SIZE);
        printf("[to server]: ");
        fgets(buf, BUF_SIZE, stdin);
        buf[strlen(buf) - 1] = '\0';

        rw_bytes = send(sockfd, buf, BUF_SIZE, 0);
        if (-1 == rw_bytes) {
            ERR("send");
        }
        
        bzero(buf, BUF_SIZE);
        rw_bytes = recv(sockfd, buf, BUF_SIZE, 0);
        if (-1 == rw_bytes) {
            ERR("recv");
        }
        printf("[from server]%s\n", buf);
    }

    if (-1 == close(sockfd)) {
        ERR("close");
    }

    return 0;
}


